<?php
declare (strict_types=1);

namespace app\middleware\ymsh;

use app\common\facade\auth\Auth;
use think\facade\Log;

class SighCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     */
    public function handle($request, \Closure $next)
    {

        $params = $request->all();
        Log::info('Java请求参数:'.json_encode($params) );
        $request_sign = $params['sign'] ?? '';

        $sign = $this->sign($params);

        if ($request_sign != $sign && isProd()) {
            return fail('验签失败');
        }
        //登录 的为总后台
        Auth::loginBySign();

        return $next($request);
    }


    public function sign($params)
    {

        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        if (isset($params['ids'])) {
            unset($params['ids']);
        }

        ksort($params);

        $values = array_values($params);
        $values_str = implode('', $values);

//        $keys = array_keys($params);
//        $keys_str = implode('', $keys);

        Log::info('生成的md5验签的字符串:'.$values_str);

        $sign_str = $values_str.'1axd@#hhjdxc';

        $sign = md5($sign_str);

        return $sign;
    }
}
